package controller.notifcations;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.notifications.CompanyNotificationsFragmentAdapter;
import define.API;
import define.Key;
import listener.notifications.CompanyNotificationsScrollListener;
import model.notifications.ArgumentsOfCompanyNotifications;
import model.notifications.CompanyNotificationsItem;
import ui.fragment.notifications.CompanyNotificationsFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class CompanyNotificationsAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private int type = 0;
    private long id = 0;
    private String ADDED_TIME = "";
    private String ELAPSED_TIME = "";
    private String CONTENTS = "";
    private String READ_STATUS = "";
    private String USER_NAME = "";
    private String USER_EMAIL = "";
    private String COMPANY_NAME = "";
    private long user_global_id = 0;
    private String SPLASH = "";
    private long company_id = 0;
    private String GROUP_NAME = "";
    private long group_id = 0;


    private String ERROR = "";
    private String STATUS = "";
    private String MSG = "";

    /**
     * The others section
     */
    private Context mContext;
    public static ArrayList <CompanyNotificationsItem> mAlCompanyNotifications = new ArrayList<>();
    public static ArrayList <Long> mAlId = new ArrayList<>();

    public CompanyNotificationsAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext.getApplicationContext(), ERROR ,
                    Toast.LENGTH_SHORT).show();
        } else {
            if (CompanyNotificationsScrollListener.currentPage > 0) {
                CompanyNotificationsFragment.companyNotificationsFragmentAdapter.notifyDataSetChanged();
            } else {
                CompanyNotificationsFragment.companyNotificationsFragmentAdapter = new CompanyNotificationsFragmentAdapter(mContext,
                        R.layout.simple_list_item_in_company_notifications_fragment,
                        mAlCompanyNotifications);
                CompanyNotificationsFragment.mLvInCompanyNotificationsFragment.setAdapter(
                        CompanyNotificationsFragment.companyNotificationsFragmentAdapter);
            }
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_COMPANY_NOTIFICATIONS);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.USER_EMAIL, params[1]));
        mListValues.add(new BasicNameValuePair(Key.USER_COMPANY_ID, params[2]));
        mListValues.add(new BasicNameValuePair(Key.GET_ALL_NOTIFICATIONS, params[3]));
        mListValues.add(new BasicNameValuePair(Key.PAGE_NUMBER, params[4]));
        mListValues.add(new BasicNameValuePair(Key.TYPE, params[5]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", CompanyNotificationsAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                MSG = mJoXml.getString(Key.MSG);
                //get mJaNotifications from mJoXml
                JSONArray mJaNotifications = mJoXml.getJSONArray(Key.NOTIFICATIONS);
                if (!"[]".equals(mJaNotifications.toString())) {
                    for (int i = 0; i < mJaNotifications.length(); i++) {
                        //get mJoNotifications from mJaNotifications
                        JSONObject mJoNotifications = mJaNotifications.getJSONObject(i);
                        //get string from mJoNotifications
                        type = mJoNotifications.getInt(Key.TYPE);
                        id = mJoNotifications.getLong(Key.ID);
                        ADDED_TIME = mJoNotifications.getString(Key.ADDED_TIME);
                        ELAPSED_TIME = mJoNotifications.getString(Key.ELAPSED_TIME);
                        CONTENTS = mJoNotifications.getString(Key.CONTENTS);
                        READ_STATUS = mJoNotifications.getString(Key.READ_STATUS);
                        //get mJoArguments from mJoNotifications
                        JSONObject mJoArguments = mJoNotifications.getJSONObject(Key.ARGUMENTS);
                        //get string from mJoArguments
                        ArgumentsOfCompanyNotifications argumentsOfCompanyNotifications = null;
                        switch (type) {
                            case 6:
                                /**
                                 * Invite to company
                                 * user_name,
                                 * user_email,
                                 * company_name,
                                 * user_global_id,
                                 * splash,
                                 * company_id
                                 */
                                USER_NAME = mJoArguments.getString(Key.USER_NAME);
                                USER_EMAIL = mJoArguments.getString(Key.USER_EMAIL);
                                COMPANY_NAME = mJoArguments.getString(Key.COMPANY_NAME);
                                user_global_id = mJoArguments.getLong(Key.USER_GLOBAL_ID);
                                SPLASH = mJoArguments.getString(Key.SPLASH);
                                company_id = mJoArguments.getLong(Key.COMPANY_ID);
                                argumentsOfCompanyNotifications = new ArgumentsOfCompanyNotifications(
                                        USER_NAME, USER_EMAIL, COMPANY_NAME,
                                        user_global_id, SPLASH,company_id,
                                        GROUP_NAME, group_id
                                );
                                break;
                            case 20:
                                /**
                                 * Invite to company group
                                 * user_name,
                                 * company_name,
                                 * user_global_id,
                                 * splash,
                                 * company_id
                                 * group_name,
                                 * group_id
                                 */
                                USER_NAME = mJoArguments.getString(Key.USER_NAME);
                                COMPANY_NAME = mJoArguments.getString(Key.COMPANY_NAME);
                                user_global_id = mJoArguments.getLong(Key.USER_GLOBAL_ID);
                                SPLASH = mJoArguments.getString(Key.SPLASH);
                                company_id = mJoArguments.getLong(Key.COMPANY_ID);
                                GROUP_NAME = mJoArguments.getString(Key.GROUP_NAME);
                                group_id = mJoArguments.getLong(Key.GROUP_ID);
                                argumentsOfCompanyNotifications = new ArgumentsOfCompanyNotifications(
                                        USER_NAME, USER_EMAIL, COMPANY_NAME,
                                        user_global_id, SPLASH,company_id,
                                        GROUP_NAME, group_id
                                );
                                break;
                        }


                        CompanyNotificationsItem companyNotificationsItem = new CompanyNotificationsItem(
                                type, id, ADDED_TIME,
                                ELAPSED_TIME, CONTENTS, READ_STATUS,
                                argumentsOfCompanyNotifications
                        );
                        //check duplicate
                        if (!mAlId.contains(id)) {
                            mAlCompanyNotifications.add(companyNotificationsItem);
                            mAlId.add(id);
                        }
                    }
                }
                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}